package com.adnaan.restaurant.controller;

import com.adnaan.restaurant.common.untils.R;
import com.adnaan.restaurant.entity.ResShop;
import com.adnaan.restaurant.mapper.ResShopMapper;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * author: adnaan
 * create:  2023-10-25 13:58
 * Description:
 */
@RestController
@RequestMapping("/api/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ResShopMapper resShopMapper;


    @GetMapping("/put")
    public R put(String key, String value) {
        System.out.println("key:" + key);
        System.out.println("value:" + value);

        stringRedisTemplate.opsForValue().set(key, value, 1, TimeUnit.DAYS);
        String v = stringRedisTemplate.opsForValue().get(key);

        Map<Object, Object> result = new HashMap<>();
        result.put("key", key);
        result.put("value", v);

        return R.success(result);

    }

    @GetMapping("/putObj")
    public R putObj(@RequestParam Long id) {
        ResShop resShop = resShopMapper.selectResShopById(id);
        String json = JSON.toJSONString(resShop);
        stringRedisTemplate.opsForValue().set(id.toString(), json, 1, TimeUnit.HOURS);

        return R.success(resShop);
    }

    @GetMapping("/getObj")
    public R getObj(@RequestParam Long id) {
        String json = stringRedisTemplate.opsForValue().get(id.toString());
        ResShop resShop = new ResShop();
        if (json == null) {
            /*
             * redis中无该信息
             * */
            resShop = resShopMapper.selectResShopById(id);
            String stringStr = JSON.toJSONString(resShop);
            stringRedisTemplate.opsForValue().set(id.toString(), stringStr, 1, TimeUnit.HOURS);
        } else {
            /*
             * redis中有该信息
             * */
            resShop = JSON.parseObject(json, ResShop.class);
        }
        return R.success(resShop);
    }


}
